package com.sencorsta.ids.game.openHandler;


import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.game.proto.GameJoinRoomByProto;
import com.sencorsta.ids.game.world.bean.Player;
import com.sencorsta.ids.game.world.bean.World;
import com.sencorsta.ids.game.world.room.Room;
import io.netty.channel.Channel;


/**
 * @author TAO
 * @description: 加入房间
 * @date 2019/11/22 14:00
 */

@ClientEvent("JoinRoom")
public class JoinRoomHandler extends OpenMessageHandler implements RedisService {

    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.debug("------------加入房间--------JoinRoom------------");
        GameJoinRoomByProto.JoinRoomRes.Builder res = GameJoinRoomByProto.JoinRoomRes.newBuilder();
        try {
            GameJoinRoomByProto.JoinRoomReq req = GameJoinRoomByProto.JoinRoomReq.parseFrom(protobuf);

            int gameId = req.getGameId();//得到加入的房间类型
            int roomId = req.getRoomId();//得到加入的房间房间Id

            Room room = World.getInstance().games.get(gameId).rooms.get(roomId);

            if (room==null){
                return error(ErrorCodeList.ROOM_IS_NULL);
            }
            if (room.status!=2){
                return error(ErrorCodeList.ROOM_NO_START);
            }

            Player player= World.getInstance().enterWorld(userId,room);
            if (player==null){
                return error(ErrorCodeList.PLAYER_IS_NULL);
            }
            res.setMaxAmount(room.maxAmount);
            res.setMinAmount(room.minAmount);
            res.setSMaxAmount(room.sMaxAmount);
            res.setSMinAmount(room.sMinAmount);
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            Out.debug();
            return responseProto(res);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR));
            return responseProto(res);
        }
    }
}
